import React, { useState, useEffect } from "react";
import {
  Card,
  Button,
  Table,
  message,
  Space,
  Input,
  Form,
  Tag,
  Divider,
} from "antd";
import userService, { User } from "../services/userService";

import http from "../services/http";

const ApiDemo: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await userService.getUsers({ page: 1, pageSize: 10 });

      setUsers(response.data.list || []);
    } catch (error) {
      console.error("获取用户列表失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleLogin = async (values: {
    username: string;
    password: string;
  }) => {
    try {
      const response = await userService.login({
        username: values.username,
        password: values.password,
      });

      localStorage.setItem("auth_token", response.data.token);
      message.success("登录成功");
    } catch (error) {}
  };

  const abortRequest = () => {
    http.cancelRequest("getUserList");
    message.info("已取消请求");
  };

  const columns = [
    {
      title: "头像",
      dataIndex: "avatar",
      key: "avatar",
      render: (avatar: string) =>
        avatar ? (
          <img
            src={avatar}
            alt="avatar"
            style={{ width: 32, height: 32, borderRadius: "50%" }}
          />
        ) : null,
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
      render: (role: string) => {
        let color = "blue";
        if (role === "admin") color = "red";
        else if (role === "developer") color = "green";
        else if (role === "tester") color = "orange";
        return <Tag color={color}>{role.toUpperCase()}</Tag>;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: number) => (
        <Tag color={status === 1 ? "green" : "red"}>
          {status === 1 ? "激活" : "禁用"}
        </Tag>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_: unknown) => (
        <Space size="middle">
          <Button size="small" type="primary">
            查看
          </Button>
          <Button size="small">编辑</Button>
          <Button size="small" danger>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: "24px" }}>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          marginBottom: "16px",
        }}
      >
        <h1>API请求示例</h1>
      </div>

      <Card title="登录请求" style={{ marginBottom: 24 }}>
        <Form
          form={form}
          layout="inline"
          onFinish={handleLogin}
          initialValues={{ username: "admin", password: "admin123" }}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input placeholder="用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title="用户列表请求" style={{ marginBottom: 24 }}>
        <Space style={{ marginBottom: 16 }}>
          <Button type="primary" onClick={fetchUsers} loading={loading}>
            获取用户列表
          </Button>
          <Button danger onClick={abortRequest}>
            取消请求
          </Button>
        </Space>

        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={false}
        />
      </Card>

      <Card title="使用说明">
        <Divider orientation="left">基本用法</Divider>
        <pre
          style={{
            background: "#f6f8fa",
            padding: "16px",
            borderRadius: "4px",
          }}
        >
          {`// 导入HTTP服务
import http from '@/services/http';

// 基本请求
const response = await http.get('/api/users');

// 带参数的请求
const user = await http.get('/api/users/123', { include: 'profile' });

// POST请求
const result = await http.post('/api/users', { 
  name: 'John Doe', 
  email: 'john@example.com' 
});

// 取消请求
http.cancelRequest('requestId');`}
        </pre>
      </Card>
    </div>
  );
};

export default ApiDemo;
